<template>
  <div>
    <div style="padding-bottom: 20px; color: #0000FF;" @click="closePage"><订单管理</div>
    <div class="information_edit">
      <div class="page_top padding_20">
        <div>订单详情</div>
        <div class="item_wrap">
          <div class="item">
            <div class="txt">订单类型</div>
            <div class="content">{{ detail.type==1?"现货":"预定" }}</div>
          </div>
          <div class="item">
            <div class="txt">订单号</div>
            <div class="content">{{ detail.orderid }}</div>
          </div>
          <div class="item">
            <div class="txt">下单时间</div>
            <div class="content">{{ detail.addtime }}</div>
          </div>
        </div>
      </div>
      <div class="page_content padding_20">
        <div class="status_wrap">
          <div class="title">
            <div class="left">当前状态：
              {{ orderStatusType[detail.orderstatus] }}
            </div>
            <div v-if="detail.orderstatus == 0 || detail.orderstatus == 5" class="right">
              <i class="el-icon-alarm-clock" />
              <span>剩余付款期限：{{ leftTime }}</span>
            </div>
          </div>
          <div v-if="detail.orderstatus == 0 || detail.orderstatus == 1" class="content">
            <div>请您第一时间设置定价，否则买家有权取消订单并取回全部定金</div>
            <div>设定定价后，买家有7天时间考虑能否接受定价，超过7天后，定金将被锁定</div>
          </div>
          <div v-if="detail.orderstatus == 2" class="content">
            <div>请您第一时间设置尾款日期，以便安排买家及时尾款</div>
            <div>该订单365天内不能补款，则该订单取消订单且定金全退</div>
          </div>
          <div v-if="detail.orderstatus == 3" class="content">
            <div>买家付款后超过30天未发货，买家有权利取消订单并退款给买家</div>
          </div>
          <div v-if="detail.orderstatus == 4||detail.orderstatus == 6" class="content">
            <div>买家已付款，请尽快安排发货，尾款时间：{{ detail.time5 }}</div>
          </div>
          <div v-if="detail.orderstatus == 5" class="content">
            <div>买家付款后超过30天未发货，买家有权利取消订单并退款给买家</div>
            <div>买家付款后超过365天未发货，系统将自动取消订单并退款给买家</div>
          </div>
          <div v-if="detail.orderstatus == 7" class="content">
            <div>商家已发货</div>
          </div>
          <div v-if="detail.orderstatus == 8" class="content">
            <div>买家已收货</div>
          </div>
          <div v-if="detail.orderstatus == 9" class="content">
            <div>订单已取消</div>
          </div>
          <div v-if="detail.orderstatus != 7 && detail.orderstatus != 8 && detail.orderstatus != 9" class="but_wrap">
            <el-row style="background: #fff;margin-bottom: 10px;">
              <el-col :span="22">
                <el-button v-if="detail.orderstatus==1||detail.orderstatus==2||detail.orderstatus==3" type="primary" @click="$router.push(`/commodity/commodity/index?showEdit=2&commodityid=${detail.commodity[0].commodityid}`)">编辑商品</el-button>
                <!-- <el-button type="primary" @click="$router.push(`/commodity/commodity/index?showEdit=2&commodityid=${detail.commodity[0].commodityid}`)">编辑商品</el-button> -->
                <!-- orderstatus 0的时候 type传1  orderstatus 3的时候 传2过来  orderstatus 5 的时候传3   其他几个 设置优惠 隐藏掉 -->
                <el-button v-if="[0, 3, 5].includes(detail.orderstatus)" style="border-color: #409EFF;color: #409EFF;" @click="dialogFormVisible=true">设置优惠减免</el-button>
                <el-button v-if="detail.orderstatus==4||detail.orderstatus==6" style="border-color: #409EFF;color: #409EFF;" @click="dialogVisible=true">发货</el-button>
                <el-button style="border-color: #409EFF;color: #409EFF;" @click="cancelOrder">取消订单</el-button>
		<el-button style="border-color: #409EFF;color: #409EFF;" @click="dialogAddressvisible=true">修改收货地址</el-button>
              </el-col>

            </el-row>
          </div>
        </div>

      </div>
      <div v-if="detail.orderstatus != 9" class="page_content padding_20">
        <div class="order_msg">
          <div class="order_item">
            <template v-if="detail.type == 2">
              <div>定金金额	￥{{ detail.yudingmoney }}</div>
              <div>优惠减免	￥{{ detail.yudingyouhuimoney }}</div>
              <!-- <div>K点支付	￥{{ detail.yudingyouhuiintegral }}</div> -->
              <!-- <div>支付金额	￥{{ detail.yudingpaymoney }}</div> -->
              <div>尾款金额	￥{{ detail.weikuanmoney }}</div>
              <div>优惠减免	￥{{ detail.weikuanyouhuimoney }}</div>
            </template>
            <template v-if="detail.type == 1">
              <div>金额	￥{{ detail.xianhuomoney }}</div>
              <div>优惠减免	￥{{ detail.xianhuoyouhuimoney }}</div>
              <!-- <div>K点支付	￥{{ detail.xianhuoyouhuiintegral }}</div> -->
              <!-- <div>支付金额	￥{{ detail.xianhuopaymoney }}</div> -->
            </template>
          </div>
          <div class="order_item">
            <div>配送方式	{{ detail.yunfeiname }}</div>
            <div>配送单号 {{ detail.yunfeiorder }}</div>
            <div>发货日期	{{ detail.yunfeistartdate }}</div>
            <div>收货日期	{{ detail.yunfeienddate }}</div>
          </div>
          <div class="order_item">
            <div>收货人	{{ detail.takeusername }}</div>
            <div>手机号码	{{ detail.takeusermobile }}</div>
            <div>地址	{{ detail.takeuseraddress }}</div>
            <div />
          </div>
        </div>
      </div>

      <div v-if="detail.commodity" class="page_content padding_20">
        <div class="goods" v-for="item in detail.commodity" :key="item.commodityid">
          <div class="goods_item" style="flex: 2;">
            <div class="title">商品</div>
            <div class="goods_msg">
              <img class="goods_img" :src="item.img" alt="">
              <div class="goods_right">
                <div class="goods_tit">
                  <p>{{ item.title}}</p>
                </div>
                <div style="color: #999;"><span>{{ item.specs }}</span></div>
              </div>
            </div>
          </div>
          <div class="goods_item">
            <div class="title">定金（元）</div>
            <div>
              {{ detail.ordermoney ? detail.ordermoney.dingjin : '' }}
            </div>
          </div>
          <div class="goods_item">
            <div class="title">尾款（元）</div>
            <div>
              {{ detail.ordermoney ? detail.ordermoney.weikuan : '' }}
            </div>
          </div>
          <div class="goods_item">
            <div class="title">总金额（元）</div>
            <div>
              {{ detail.ordermoney ? detail.ordermoney.allmoney : '' }}
            </div>
          </div>
        </div>
      </div>

      <div v-if="detail.orderstatus != 9" class="page_content padding_20">
        <div class="total_wrap">
          <div v-if="detail.ordermoney" class="total">
            <div class="total_item"><span>订单总额</span><span>￥{{ detail.ordermoney.allmoney }}</span></div>
            <div class="total_item"><span>运费</span><span>￥{{ detail.ordermoney.yunfei }}</span></div>
            <div class="total_item"><span>优惠抵扣</span><span>-￥{{ detail.ordermoney.youhui }}</span></div>
            <div class="total_item"><span>K点抵扣</span><span>-￥{{ detail.ordermoney.integral }}</span></div>
            <div class="total_item"><span>已付金额</span><span>￥{{ detail.ordermoney.yifumoney }}</span></div>
            <div class="total_item"><span>待付金额</span><span style="color: red;font-size: 20px;font-weight: 600;">￥{{ detail.ordermoney.daifumoney }}</span></div>
          </div>
        </div>
      </div>

      <!-- <div class="page_foot padding_20">
				<div>
					<el-button @click="closePage" style="border-color: #409EFF;color: #409EFF;">取 消</el-button>
					<el-button @click="saveuserinfo" type="primary">保 存</el-button>
				</div>
			</div> -->
    </div>

    <el-dialog title="设置优惠减免" :visible.sync="dialogFormVisible" :close-on-click-modal="false">
      <div>
        <div>
          <div class="ad_item" style="align-items: center;margin-bottom: 10px;"><span>优惠金额（元）</span></div>
          <el-input v-model="money" placeholder="请输入金额"  @keyup.native="money=money.replace(/[^\d.]/g, '')" />
        </div>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="orderYouhui">确 定</el-button>
      </div>
    </el-dialog>

    <el-dialog title="发货" :visible.sync="dialogVisible" :close-on-click-modal="false">
      <el-form ref="form" :model="form" :rules="rules" label-position="top">
        <el-form-item
          label="配送单号"
          prop="fareorder"
        >
          <el-input v-model="form.fareorder" autocomplete="off" :maxlength="30" @keyup.native="form.fareorder=form.fareorder.replace(/[^\d\w]/g, '')" clearable />
        </el-form-item>
        <el-form-item
          label="快递公司"
          prop="name"
        >
          <!-- <el-input v-model.number="form.name" disabled autocomplete="off" /> -->
          <el-select v-model="form.code" placeholder="快递公司">
            <el-option
              v-for="item in company"
              :key="item.code"
              :label="item.name"
              :value="item.code"
            />
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible=false">取 消</el-button>
        <el-button type="primary" @click="orderFahuo">确 定</el-button>
      </div>
    </el-dialog>


    <el-dialog title="修改收货地址" :visible.sync="dialogAddressvisible" :before-close="closeDialog" :close-on-click-modal="clickModalClose" :width="dialogWidth">
      <el-form ref="ruleForm" :model="ruleForm" :rules="rules2" label-position="top">
         <el-form-item prop="name" label="收货人姓名" :rules2="[{ required: true, message: '请输入收货人姓名', trigger: 'blur' }]">
                    <el-input v-model.trim="ruleForm.name" :maxlength="16" clearable @keyup.native="ruleForm.name=ruleForm.name.replace(/\s+/g, '')" @keyup.enter.native="onSubmit" />
                </el-form-item>
                <el-form-item prop="mobile" label="手机号" :rules2="[{ required: true, message: '请输入手机号', trigger: 'blur' }]">
                    <el-input v-model.trim="ruleForm.mobile" :maxlength="11" clearable @keyup.native="ruleForm.mobile=ruleForm.mobile.replace(/[^\d]/g, '')" @keyup.enter.native="onSubmit" />
                </el-form-item>
		<el-form-item prop="areacode" label="所在区域" :rules="[{ required: true, message: '请选择所在区域', trigger: 'change' }]">
                    <!-- <el-cascader v-if="showCascader" v-model="areaArr" :props="{ lazy: true, lazyLoad: lazyLoad }" clearable @change="onChange" /> -->
                    <!-- <el-cascader :props="props"></el-cascader> -->
                    <province-city-area ref="provinceCityArea" :provincecode-default="ruleForm.provincecode" :citycode-default="ruleForm.citycode" :areacode-default="ruleForm.areacode" @setFullAddress="getFullAddress" />
                </el-form-item>
                <el-form-item prop="address" label="详细地址" :rules2="[{ required: true, message: '请输入详细地址', trigger: 'blur' }]">
                    <el-input v-model="ruleForm.address" type="textarea" size="medium" placeholder="请输入详细地址" maxlength="200" show-word-limit clearable @keyup.enter.native="onSubmit" />
                </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogAddressvisible=false">取 消</el-button>
        <el-button type="primary" @click="orderAddress">确 定</el-button>
      </div>
    </el-dialog>




  </div>
</template>

<script>
import { formatDuring } from '@/utils'
import { getComcode } from '@/api/aftermarket'
import { orderDetails, orderYouhui, cancelOrder, orderFahuo, orderAddress } from '@/api/order'
import provinceCityArea from '@/components/provinceCityArea'
export default {
  props: ['editdata'],
   components: {
        provinceCityArea
    },
  data(vm) {
    const validateFareorder = async(rule, value, callback) => {
      if (!value) {
        return callback('请输入配送单号')
      } else {
        // 请求查询快递公司，如果查不到则单号有问题
        const res = await getComcode({ fareorder: value })
        const detail = res.detail
        if (detail && detail.status === 2) {
          vm.company = []
          vm.form.code = ''
          vm.form.name = ''
          return callback('快递查询失败，请检查配送单号是否正确')
        } else {
          // vm.form.code = detail.company[0].code
          // vm.form.name = detail.company[0].name
          vm.company = detail.company || []
          if(vm.company[0]) vm.form.code = vm.company[0].code
          callback()
        }
      }
    }
    return {
      dialogFormVisible: false,
      dialogAddressvisible: false,
      dialogVisible: false,
      orderid: '',
      detail: {},
      company: [], // 通过配送单号查询出来的快递公司列表
      form: {
        fareorder: '',
        name: '',
        code: ''
      },
      rules: {
        fareorder: [
          { validator: validateFareorder, trigger: 'blur' }
        ]
	
      },

      money: '',
      expressid: '',
      // 0 预订，未付定金  1 预订，未定价 2 预订，已定价（没有资格付钱的那种） 3预订待付尾款  4 预订待发货  5 现货,待付款 6现货,已付款 待发货 7已发货 8已完成 9 已取消  
      orderStatusType: [
        '预订，未付定金',
        '预订，未定价',
        '预订，已定价',
        '预订待付尾款',
        '预订待发货',
        '现货,待付款',
        '现货,已付款 待发货',
        '已发货',
        '已完成',
        '已取消'
      ],
      leftTime: '', // 限制中的剩余截止时间
      timer: null,
      ruleForm: {
		orderid: '',
                name: '',
                mobile: '',
                address: '',
                provincecode: '',
                citycode: '',
                areacode: ''
            },
    }
  },
  created() {
    console.log(this.editdata)
    if (this.editdata) {
      this.orderid = this.editdata.orderid
      this.ruleForm.orderid = this.editdata.orderid
      this.orderDetails()
    } else {

    }
  },
  methods: {
    // 刷新剩余付款时间
    updateLeftTime() {
        const self = this
        window.clearInterval(this.timer)
        // 1秒刷新一次
        this.timer = window.setInterval(async() => {
          const addTime = new Date(this.detail.addtime).getTime()
          const nowTime = new Date().getTime()
          // 最大时限2小时
          const MaxTime = 2 * 60 * 60 * 1000
          const leftTime = MaxTime - (nowTime - addTime)
          const leftTimeStr = leftTime > 0 ? formatDuring(leftTime) : 0
          self.leftTime = leftTimeStr
        }, 1000)
    },
    closePage() {
      this.$parent.closeEditpage()
      if(this.timer) window.clearInterval(this.timer)
      this.timer = null
      // this.$parent.getData(1);
    },
    orderDetails() {
      orderDetails({ orderid: this.orderid }).then(res => {
        this.detail = Object.assign({}, res.detail)
        this.updateLeftTime()
      })
    },
	getFullAddress(addressObj) {
	    console.log('full address', addressObj)
	    this.ruleForm.provincecode = addressObj.province.code
	    this.ruleForm.citycode = addressObj.city.code
	    this.ruleForm.areacode = addressObj.area.code
	    // this.ruleForm.address = addressObj.province.name + addressObj.city.name + addressObj.area.name
	},
    orderYouhui() {
      if(!this.money) {
        this.$message('优惠金额不能为空')
        return
      }
      // 预定无定价，优惠减免金额不能大于定金
      if(this.detail.type==2) {
        const ordermoney = this.detail.ordermoney
        if(Number(ordermoney.allmoney) === 0 && Number(this.money) > Number(ordermoney.dingjin)) {  
          this.$message.error('预定无定价，优惠减免金额不能大于定金')
          return
        } else if(Number(ordermoney.allmoney) > 0 && Number(this.money) > Number(ordermoney.weikuan)) {
          this.$message.error('预定有定价，优惠减免金额不能大于待补款金额')
          return
        }
      } else if(this.detail.type==1 && Number(this.money) > Number(ordermoney.dingjin)) { // 现货的优惠减免金额不能大于定金
        this.$message.error('现货的优惠减免金额不能大于定金')
        return
      }
      // type:1 预订未付定金阶段优惠 2预订付尾款阶段优惠 3现货未付款阶段优惠
      // orderstatus 0的时候 type传1  orderstatus 3的时候 传2过来  orderstatus 5 的时候传3   其他几个 设置优惠 隐藏掉
      let type = ''
      switch (this.detail.orderstatus) {
        case 0:
          type = 1
          break
        case 3:
          type = 2
          break
        case 5:
          type = 3
          break
        default:
      }
      orderYouhui({
        orderid: this.orderid,
        type: type,
        money: this.money
      }).then(res => {
        this.dialogFormVisible = false
        this.$message({
          type: 'info',
          message: res.msg
        })
        this.orderDetails()
      })
    },
    cancelOrder() {
      const self = this
      this.$confirm('此操作将取消该订单, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        cancelOrder({
          orderid: this.orderid
        }).then(response => {
          self.$message({
            message: '操作成功',
            type: 'success'
          })
          this.orderDetails()
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },
    orderFahuo() {
      const self = this
      this.$refs['form'].validate(async(valid) => {
        if (valid) {
          orderFahuo({ orderid: this.orderid, fareorder: this.form.fareorder, farecomcode: this.form.code }).then(res => {
            // if(res && res.detail.status === 1) {
            self.$message({
              message: res.msg,
              type: res.detail.status === 1 ? 'success' : 'error'
            })
            if(res.detail.status === 1) {
              this.dialogVisible = false
              this.orderDetails()
            }
            // }
          })
        }
      })
    },




     async orderAddress() {
            this.$refs['ruleForm'].validate(async valid => {
                if (valid) {
                    const res =  await orderAddress(this.ruleForm) 
		    if(res.detail.status === 1) {
		      this.dialogAddressvisible = false
		      this.orderDetails()
		    }
                   
                }
            })
        }


  }
}
</script>

<style>

</style>
<style lang="less" scoped>
.padding_20{
	padding: 20px;
}

.information_edit{
	border: 1px solid #ccc;
	background: #fff;
}

.page_top{
	font-size: 16px;
	font-weight: 600;
	border-bottom: 1px solid #ccc;
	.item_wrap{
		color: #999;
		display: flex;
		margin-top: 20px;
		.item{
			flex: 1;
			.txt{font-size: 14px;}
			.content{font-size: 18px;}
		}
	}
}
.page_content{
	border-bottom: 1px solid #ccc;
	.status_wrap{
		.title{
			display: flex;
			justify-content: space-between;
			.right{
				color: #999;
			}
		}
		.content{
			color: #999;
			font-size: 12px;
			line-height: 2;
			padding: 10px 0;
		}
	}
	.order_msg{
		display: flex;
		justify-content: center;
		margin-bottom: 20px;
		.order_item{
			flex: 1;
			text-align: center;
			color: #999;
			line-height: 1.4;
		}
	}
	.goods{
		display: flex;
		.goods_item{
			flex: 1;
			.title{
				color: #999;
				font-weight: 600;
				margin-bottom: 10px;
			}
			.goods_msg{
				display: flex;
				.goods_img{
					width: 100px;
					height: 100px;
				}
				.goods_right{
          padding: 0 10px;
					display: flex;
					flex-direction: column;
					justify-content: space-between;
					.goods_tit{
						text-overflow: -o-ellipsis-lastline;
						overflow: hidden;
						text-overflow: ellipsis;
						display: -webkit-box;
						-webkit-line-clamp: 2;
						line-clamp: 2;
            -webkit-box-orient: vertical;
            > p {
              margin: 0 0 10px;
            }
					}
				}
			}
		}
	}
	.total_wrap{
		display: flex;
		flex-direction: row-reverse;
		.total{
			width: 200px;
			.total_item{
				display: flex;
				justify-content: space-between;
				color: #999;
				line-height: 2;
			}
		}
	}

}

.ad_item{
	margin-top: 10px;
}

.page_foot{
	display: flex;
	justify-content: flex-end;
}

</style>
